import HttpStatusCode from '../helpers/http-status';
import { forEach, stringToNumber, jsonParse } from '../utils.js';

/**
 * 序列化响应头
 * @param {*} headerText 
 * @returns 
 */
function parseResponseHeader(headerText) {
    const resArr = headerText.trim().split(/[\r\n]+/);
    const res = {};
    while (resArr.length > 0) {
        const [key, value] = resArr.shift().split(': ');
        res[key.replace('\r')] = stringToNumber(value.trim().replace('\r'));
    }
    return res;
}

/**
 * XHR 请求适配器
 * @param {*} config 
 * @returns 
 */
function Adapter(config) {
    return new Promise(function dispatchXhrRequest(resolve, reject) {
        const url = config.url;
        const method = (config.method || 'get').toUpperCase();
        const requestData = JSON.stringify(config.data || {});
        const responseType = config.responseType;
        const requestURL = config.baseUrl + config.url;
        const requestHeaders = config.headers || {};
        const request = new XMLHttpRequest();

        // 建立连接
        request.open(method, requestURL, true);

        // 请求结束事件
        function onloadend() {
            if (!request) {
                return '';
            }

            const responseData =
                !responseType ||
                responseType === 'text' ||
                responseType === 'json'
                    ? jsonParse(request.responseText)
                    : request.response;
            

            // 获取响应头
            const responseHeader = parseResponseHeader(request.getAllResponseHeaders());


            const response = {
                data: responseData,
                status: request.status,
                statusText: request.statusText,
                headers: responseHeader,
                config,
                request,
            };

            if (request.status === HttpStatusCode.Ok) {
                resolve(response);
            } else {
                reject(response);
            }
        }

        if ('onloadend' in request) {
            request.onloadend = onloadend;
        } else {
            request.onreadystatechange = function () {
                if (!request || request.readyState !== 4) {
                    return;
                }

                if (
                    request.status === 0 &&
                    !(
                        request.responseURL &&
                        request.responseURL.indexOf('file:') === 0
                    )
                ) {
                    return;
                }

                setTimeout(onloadend);
            };
        }

        // 绑定对应的响应事件
        request.onerror = function handlerError() {};
        request.onload = function handlerLoad() {};
        request.timeout = function handlerTimeout() {};

        // 设置header
        if ('setRequestHeader' in request) {
            // 设置可以访问自定义请求头，否则无法访问
            request.setRequestHeader('Access-Control-Expose-Headers', Object.keys(requestHeaders).join(', '))

            forEach(requestHeaders, function setRequestHeader(val, key) {
                request.setRequestHeader(key, val);
            });
        }

        // 发起
        request.send(requestData);
    });
}

export { Adapter };
